<template>
  <div class="login-container">
    <div class="login-box" :class="{ 'expanded': isExpanded }">
      <div class="login-header" @click="toggleExpand">
        <h2>系统登录</h2>
        <div class="expand-icon">{{ isExpanded ? '−' : '+' }}</div>
      </div>
      <form class="login-form" :class="{ 'form-visible': isExpanded }" @submit.prevent="handleLogin">
        <div class="form-item">
          <i class="el-icon-user"></i>
          <input type="text" v-model="username" placeholder="用户名" autocomplete="username" />
        </div>
        <div class="form-item">
          <i class="el-icon-lock"></i>
          <input type="password" v-model="password" placeholder="密码" autocomplete="current-password" />
        </div>
        <div class="form-item captcha-container">
          <i class="el-icon-picture"></i>
          <input type="text" v-model="captcha" placeholder="验证码" class="captcha-input" autocomplete="off" />
          <div class="captcha-image" @click="refreshCaptcha">
            <img v-if="captchaImage" :src="captchaImage" alt="验证码" width="100" height="40" />
            <div class="refresh-icon">↻</div>
          </div>
        </div>
        <div class="form-item remember">
          <input type="checkbox" id="remember" v-model="rememberMe" />
          <label for="remember">记住密码</label>
        </div>
        <div class="form-item">
          <button type="submit" class="login-button">登 录</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import {apiWreit} from '@/Ulter/AxiosHepler'
import axios from 'axios';
import { UserManager } from '@/utils/userManager'

export default {
  name: 'Login',
  data() {
    return {
      username: '',
      password: '',
      rememberMe: false,
      captcha: '',
      captchaId: '', // 存储验证码ID
      captchaImage: '', // 存储验证码图片base64
      isExpanded: false
    }
  },
  methods: {
    // 获取验证码
    getCaptcha() {
      // 清除之前的验证码
      this.captchaImage = '';
      this.captchaId = '';
      
      console.log('开始获取验证码...');
      
      // 创建请求配置，确保不带Authorization头
      const config = {
        headers: {}
      };
      
      apiWreit.get('/api/Mange/GetCaptcha/captcha', config)
        .then(res => {
          console.log('验证码获取成功');
          if (res.data && res.data.imageBase64) {
            this.captchaImage = res.data.imageBase64;
            this.captchaId = res.data.captchaId;
          } else {
            console.warn('验证码响应格式不正确:', res.data);
            ElMessage.error('获取验证码失败，请刷新页面重试');
          }
        })
        .catch(error => {
          console.error('获取验证码失败:', error);

          // 检查是否是网络连接问题
          if (error.code === 'NETWORK_ERROR' || error.message.includes('Network Error')) {
            ElMessage.error('网络连接失败，请检查后端服务是否启动 (http://localhost:34405)');
            return;
          }

          // 尝试不带任何头部再次请求
          console.log('尝试使用原生axios获取验证码...');
          axios.get('http://localhost:34405/api/Mange/GetCaptcha/captcha')
            .then(res => {
              console.log('使用原生axios获取验证码成功');
              if (res.data && res.data.imageBase64) {
                this.captchaImage = res.data.imageBase64;
                this.captchaId = res.data.captchaId;
              } else {
                console.warn('验证码响应格式不正确:', res.data);
                ElMessage.error('获取验证码失败，请刷新页面重试');
              }
            })
            .catch(err => {
              console.error('使用原生axios获取验证码也失败:', err);
              if (err.code === 'NETWORK_ERROR' || err.message.includes('Network Error')) {
                ElMessage.error('无法连接到后端服务，请确保服务器正在运行');
              } else {
                ElMessage.error('获取验证码失败，请检查网络连接或稍后重试');
              }
            });
        });
    },
    
    // 刷新验证码
    refreshCaptcha() {
      if (this.captchaId) {
        // 如果已有验证码ID，则使用刷新接口
        console.log('使用刷新接口更新验证码...');
        
        // 创建请求配置，确保不带Authorization头
        const config = {
          headers: {}
        };
        
        apiWreit.get(`/api/Mange/RefreshCaptcha/captcha/refresh/${this.captchaId}`, config)
          .then(res => {
            console.log('验证码刷新成功');
            if (res.data && res.data.imageBase64) {
              this.captchaImage = res.data.imageBase64;
              this.captchaId = res.data.captchaId;
              this.captcha = '';
            } else {
              console.warn('验证码响应格式不正确:', res.data);
              this.getCaptcha(); // 获取新验证码
            }
          })
          .catch(error => {
            console.error('刷新验证码失败:', error);
            // 如果刷新失败，回退到获取新验证码
            this.getCaptcha();
          });
      } else {
        // 如果没有验证码ID，则获取新验证码
        this.getCaptcha();
      }
      this.captcha = '';
    },
    
    // 验证验证码
    verifyCaptcha() {
      return new Promise((resolve, reject) => {
        if (!this.captcha) {
          ElMessage.error('请输入验证码');
          reject(new Error('验证码为空'));
          return;
        }
        
        // 创建请求配置，确保不带Authorization头
        const config = {
          headers: {}
        };
        
        apiWreit.post('/api/Mange/VerifyCaptcha/captcha/verify', {
          captchaId: this.captchaId,
          captchaCode: this.captcha
        }, config)
          .then(res => {
            if (res.data && res.data.isValid) {
              resolve(true);
            } else {
              ElMessage.error('验证码错误');
              this.refreshCaptcha();
              reject(new Error('验证码错误'));
            }
          })
          .catch(error => {
            console.error('验证码验证失败:', error);
            ElMessage.error('验证码验证失败');
            this.refreshCaptcha();
            reject(error);
          });
      });
    },
    
    // 保存用户信息
    saveUserData(userData) {
      // 使用 UserManager 保存用户数据
      if (userData) {
        // 如果没有realName，使用username作为备用
        if (!userData.realName && userData.username) {
          userData.realName = userData.username;
        }

        UserManager.saveUserInfo(userData);
      }
      
      // 如果勾选了"记住密码"，则保存用户名和密码
      if (this.rememberMe) {
        localStorage.setItem('rememberedUsername', this.username);
        localStorage.setItem('rememberedPassword', btoa(this.password)); // 使用base64简单编码
        console.log('用户凭据已保存（记住密码）');
      } else {
        // 如果未勾选，则清除之前可能保存的记住密码信息
        localStorage.removeItem('rememberedUsername');
        localStorage.removeItem('rememberedPassword');
        console.log('用户凭据已清除（未勾选记住密码）');
      }
    },
    
    // 加载记住的用户名和密码
    loadRememberedCredentials() {
      const username = localStorage.getItem('rememberedUsername');
      const encodedPassword = localStorage.getItem('rememberedPassword');
      
      if (username && encodedPassword) {
        try {
          this.username = username;
          this.password = atob(encodedPassword); // 解码base64
          this.rememberMe = true;
          console.log('已加载保存的用户凭据');
        } catch (e) {
          console.error('解析保存的凭据失败', e);
        }
      }
    },
    
    // 提取和保存令牌
    extractAndSaveToken(response) {
      // 从响应体中获取令牌 - 根据截图，token在data.token字段中
      let token = null;
      
      // 检查响应体中是否有token
      if (response.data && response.data.data && response.data.data.token) {
        token = response.data.data.token;
        console.log('从响应体data.token字段获取到令牌');
      }
      
      // 保存token到localStorage
      if (token) {
        localStorage.setItem('token', token);
        console.log('令牌已保存到localStorage:', token.substring(0, 20) + '...');
      } else {
        console.warn('未找到令牌，可能需要检查API响应格式');
      }
      
      return token;
    },
    
    handleLogin() {
      if (!this.username || !this.password) {
        ElMessage.error('请输入用户名和密码');
        return;
      }
      
      this.verifyCaptcha()
        .then(() => {
          // 验证码验证成功，执行登录
          console.log('开始登录请求...');
          
          // 准备登录请求数据
          const loginData = {
            username: this.username,
            password: this.password
          };
          
          console.log('发送登录请求:', loginData);
          
          // 发送登录请求
          apiWreit.post('/api/Mange/LoginUser', loginData)
            .then(res => {
              console.log('登录响应:', res);
              
              // 检查响应状态码
              if (res.status !== 200) {
                throw new Error(`服务器返回非200状态码: ${res.status}`);
              }
              
              // 检查响应数据格式
              if (!res.data) {
                throw new Error('服务器返回空数据');
              }
              
              // 检查业务状态码
              if (res.data.code === 100) {
                console.log('登录成功，业务状态码:', res.data.code);
                
                // 获取用户数据
                const userData = res.data.data;
                if (!userData) {
                  console.warn('响应中没有用户数据');
                } else {
                  console.log('获取到用户数据:', userData);
                }
                
                // 保存用户数据
                this.saveUserData(userData);
                
                // 提取和保存令牌
                this.extractAndSaveToken(res);
                
                // 显示成功消息
                ElMessage.success(res.data.message || '登录成功');
                
                // 延迟跳转，确保数据已保存
                setTimeout(() => this.navigateToMain(), 500);
              } else {
                // 登录失败，显示错误消息
                console.error('登录失败，业务状态码:', res.data.code);
                ElMessage.error(res.data.message || '登录失败，请检查用户名和密码');
              }
            })
            .catch(error => {
              console.error('登录请求失败:', error);
              
              // 提取详细错误信息
              let errorMsg = this.extractErrorMessage(error);
              ElMessage.error(errorMsg);
            });
        })
        .catch(() => {
          // 验证码验证失败的处理已在verifyCaptcha中完成
        });
    },
    
    // 提取错误信息
    extractErrorMessage(error) {
      let errorMsg = '登录请求失败，请稍后重试';
      
      if (error.response) {
        if (error.response.data && error.response.data.message) {
          errorMsg = error.response.data.message;
        } else {
          errorMsg = `服务器返回错误: ${error.response.status} ${error.response.statusText || ''}`;
        }
      } else if (error.request) {
        errorMsg = '服务器未响应，请检查网络连接';
      } else {
        errorMsg = error.message || errorMsg;
      }
      
      return errorMsg;
    },
    
    // 导航到主页
    navigateToMain() {
      // 跳转到主页
      try {
        console.log('准备跳转到主页...');
        this.$router.push('/Main').catch(err => {
          console.error('路由跳转错误:', err);
          // 如果导航被阻止，尝试使用window.location
          window.location.href = '/Main';
        });
      } catch (e) {
        console.error('跳转到主页时出错:', e);
        // 使用window.location作为备选方案
        window.location.href = '/Main';
      }
    },
    
    toggleExpand() {
      this.isExpanded = !this.isExpanded;
    }
  },
  
  mounted() {
    // 获取验证码
    this.getCaptcha();
    // 默认展开登录框
    this.isExpanded = true;
    // 加载记住的用户名和密码
    this.loadRememberedCredentials();
    
    // 清除可能存在的过期令牌
    localStorage.removeItem('token');
    localStorage.removeItem('token_timestamp');
    console.log('已清除之前的登录状态');
  }
}
</script>

<style scoped>
/* 全局样式重置，确保页面占满整个视口 */
:deep(html), :deep(body), :deep(#app) {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url("../images/Log1.jpg");
  background-size: cover;
  background-position: center;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.login-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
}

.login-box {
  width: 400px;
  padding: 40px;
  /* background-color: rgba(255, 255, 255, 0.9); */
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
  position: relative;
  z-index: 1;
  transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  transform-style: preserve-3d;
  perspective: 1000px;
  background-color: rgba(255, 255, 255, 0.9);
}

.login-box.expanded {
  height: auto;
  max-height: 600px;
  transform: rotateX(0deg) translateZ(0);
}

.login-box:not(.expanded) {
  height: 80px;
  max-height: 80px;
  transform: rotateX(-20deg) translateZ(-50px);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  transition: all 0.3s ease;
  transform-style: preserve-3d;
}

.login-header:hover {
  background-color: rgba(64, 158, 255, 0.1);
  border-radius: 6px;
  padding: 10px;
  margin: -10px -10px 20px -10px;
  transform: translateZ(10px);
}

.expand-icon {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: rgba(64, 158, 255, 0.1);
  transition: all 0.3s ease;
  transform-style: preserve-3d;
}

.expand-icon:hover {
  background-color: rgba(64, 158, 255, 0.2);
  transform: scale(1.1) rotateY(180deg);
}

.login-header h2 {
  font-size: 28px;
  color: #333;
  margin: 0;
}

.form-item {
  margin-bottom: 20px;
  position: relative;
}

.form-item i {
  position: absolute;
  left: 10px;
  top: 12px;
  color: #888;
}

.form-item input[type="text"],
.form-item input[type="password"] {
  width: 100%;
  padding: 12px 15px 12px 35px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: all 0.3s;
  box-sizing: border-box;
}

.form-item input:focus {
  border-color: #409EFF;
  outline: none;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}

.form-item.remember {
  display: flex;
  align-items: center;
}

.form-item.remember input {
  margin-right: 8px;
}

.login-button {
  width: 100%;
  padding: 12px;
  background-color: #409EFF;
  border: none;
  border-radius: 4px;
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-button:hover {
  background-color: #66b1ff;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-input {
  flex: 1;
  padding: 12px 15px 12px 35px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: all 0.3s;
}

.captcha-input:focus {
  border-color: #409EFF;
  outline: none;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}

.captcha-image {
  position: relative;
  cursor: pointer;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s;
}

.captcha-image:hover {
  border-color: #409EFF;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.3);
}

.captcha-image img {
  display: block;
  background-color: #f0f0f0;
}

.refresh-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  opacity: 0;
  transition: opacity 0.3s;
}

.captcha-image:hover .refresh-icon {
  opacity: 1;
}

.login-form {
  opacity: 0;
  transform: translateY(-30px) rotateX(-90deg);
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  pointer-events: none;
  transform-style: preserve-3d;
  transform-origin: top center;
}

.login-form.form-visible {
  opacity: 1;
  transform: translateY(0) rotateX(0deg);
  pointer-events: auto;
}

.form-item {
  transform-style: preserve-3d;
  transition: all 0.3s ease;
}

.form-item:nth-child(1) { transition-delay: 0.1s; }
.form-item:nth-child(2) { transition-delay: 0.2s; }
.form-item:nth-child(3) { transition-delay: 0.3s; }
.form-item:nth-child(4) { transition-delay: 0.4s; }
.form-item:nth-child(5) { transition-delay: 0.5s; }

.login-form:not(.form-visible) .form-item {
  transform: translateZ(-20px) rotateX(-15deg);
  opacity: 0;
}

.login-form.form-visible .form-item {
  transform: translateZ(0) rotateX(0deg);
  opacity: 1;
}
</style>
